package Server;


import java.io.*;
import java.net.*;
import util.*;

public class TCPServer extends Thread
{
	private int portNo = 0;
	private Model mym;
	private Logger log;

	public TCPServer(int portNo, Model m, Logger l)
	{
		this.mym = m;	
		this.portNo = portNo;
		this.log = l;
	}
	
	public void run()
	{
		System.out.println("Server started...");
		try
		{
			// Create a server socket
			ServerSocket serverSocket = new ServerSocket(this.portNo);

			// To number a client
			int clientNo = 1;

			while (true)
			{
				System.out.println("Waiting for incomming connections...");
				// Listen for a new connection request
				Socket connectToClient = serverSocket.accept();

				// Print the new connect number on the console
				System.out.println("\n\nConnection accepted: " + connectToClient);

				System.out.println("Start thread for client: " + clientNo);

				// Find the client's hostname, and IP address
				InetAddress clientInetAddress = connectToClient.getInetAddress();
				System.out.println("Client " + clientNo + "'s hostname is " + clientInetAddress.getHostName());
				System.out.println("Client " + clientNo + "'s IP Address is " + clientInetAddress.getHostAddress());

				// Create a new thread for the connection
				HandleAClient thread = new HandleAClient(connectToClient, mym, log);

				// Start the new thread
				thread.start();

				// Increment clientNo
				clientNo++;
			}
		}
		catch(IOException ex)
		{
			System.err.println(ex);
		}
	}
}